#include "FreeModbus_cbk.h"
#include "Modbus_lcfg.h"


extern uint16_t pu16ModbusGetInfoTableIndex(uint16_t mBAddr);
eMBErrorCode eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress,USHORT usNRegs, eMBRegisterMode eMode )
{
    uint16_t i , u16RegValue , u16NBytes = usNRegs * 2 ;
    uint16_t * ramaddr;
    uint16_t u16MbTableIndex = pu16ModbusGetInfoTableIndex(usAddress);

    if( ( (u16MbTableIndex + usNRegs) > MODBUS_REG_NUM) ){
        return MB_ENOREG;
    }

    if( pucRegBuffer == NULL ){
        return MB_EINVAL;
    }

    if( MB_REG_READ == eMode )
    {
       for( i = 0; i < u16NBytes; i+=2 )
       {
           if( ( ramaddr = ModbusInfoTable[u16MbTableIndex].ramAddr ) != NULL )
           {
               u16RegValue = *(ramaddr);
               pucRegBuffer[i] = U16GetHighByte(u16RegValue);
               pucRegBuffer[i+1] = U16GetLowByte(u16RegValue);
               u16MbTableIndex++;
           }
           else{
               return MB_EINVAL;            
           }
       }
    }
    else if( MB_REG_WRITE == eMode )
    {
       #if WRITE_ENCRIPED==1
       /*写入数据密码校验*/
       uint16_t code = (uint16_t)(pucRegBuffer[u16NBytes-2]<<8) | (pucRegBuffer[u16NBytes-1]);
       if( code != CODE_VALUE){
           return MB_EPORTERR;
       }
       for( i = 0; i < u16NBytes - 2; i+=2 )/*写入数据扣除两字节密码*/
       #else
       for( i = 0; i < u16NBytes; i+=2 )
       #endif
       {
           em_ModbusRw regRwType = ModbusInfoTable[u16MbTableIndex].regRwType;
           ramaddr = ModbusInfoTable[u16MbTableIndex].ramAddr;
           if ( ( ramaddr==NULL ) || (regRwType == R)){
               return MB_ENOREG;                
           }
           *ramaddr = pucRegBuffer[i]<<8 | pucRegBuffer[i+1];
           u16MbTableIndex++;
       }

//        vParamCheck();
    }
    return MB_ENOERR;
}


